﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HandyControl.Controls;
using MyHelper;
using ScaleDataInterpreter;
using clf.weighing.entity;
using Button = System.Windows.Controls.Button;
using Size = System.Windows.Size;

namespace weighing
{
    /// <summary>
    /// ScaleWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ScaleWindow : GlowWindow
    {
        #region variables
        public List<ScaleVo>? mScaleVos;
        public List<ScaleBrandVo>? mScaleBrandVos = new();
        public List<ScaleSeriesVo>? mScaleSeriesVos = new();
        public ScaleVo mCurrentScale = new(new Scale());
        private bool isEdit = false;
        private bool isEditing = false;
        private bool isBindingValue = false;
        #endregion


        public ScaleWindow()
        {
            InitializeComponent();
            CommonFunction.ShowCustomIcon(this);
        }

        #region window event

        private void Scale_Window_Loaded(object sender, RoutedEventArgs e)
        {


        }

        private void Scale_Window_ContentRendered(object sender, EventArgs e)
        {
            FillData();
            var coms = System.IO.Ports.SerialPort.GetPortNames();
            //String[] coms = new String[]{ "Com1", "Com2" };
            this.comCb.ItemsSource = coms;
#if DEBUG
            if (coms.Length <= 0)
            {
                coms = new String[] { "Com3", "Com4" };
                this.comCb.ItemsSource = coms;
            }
#endif
        }
        #endregion

        private void FillData()
        {
            this.DataLv.ItemsSource = null;
            var list = ScaleDao.Instance.GetList();
            mScaleVos = list?.Select((i) => { return new ScaleVo(i); }).ToList();
            this.DataLv.ItemsSource = mScaleVos;
            if (mScaleVos?.Count >= 2)
            {
                this.addBtn.Visibility = Visibility.Collapsed;
            }
            else
            {
                this.addBtn.Visibility = Visibility.Visible;
            }
        }

        private void SetBrandCbItemSource()
        {
            if (mScaleBrandVos.Count <= 0)
            {
                var list = ScaleBrandDao.Instance.GetList();                
                mScaleBrandVos = list?.Select((i) => { return new ScaleBrandVo(i); }).ToList();
            }
            this.brandCb.ItemsSource = mScaleBrandVos;
        }
        private void DataLv_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isEditing)
            {
                return;
            }
            isEdit = false;
            this.DrawerHeaderTB.Text = "新增";
            this.AddDrawerRight.IsOpen = true;

            this.SetBrandCbItemSource();
        }

        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            isEdit = true;
            isEditing = true;
            this.DrawerHeaderTB.Text = "修改";
            var button = sender as Button;
            var vo = button?.Tag as ScaleVo;
            BindEditValue(vo.mScale);
            mCurrentScale = vo;
            this.AddDrawerRight.IsOpen = true;
            this.SetBrandCbItemSource();
            for (int i = 0; i < mScaleBrandVos.Count; i++)
            {
                if (mCurrentScale.Brand == mScaleBrandVos[i].BrandName)
                {
                    this.brandCb.SelectedIndex = i;
                }
            }
        }

        private void DelBtn_Click(object sender, RoutedEventArgs e)
        {
            Button? button = sender as Button;
            var vo = button?.Tag as ScaleVo;
            string msg = "是否要删除 ：" + vo?.Name;
            var result = CommonFunction.Ask(msg, this);
            if (result == MessageBoxResult.Yes)
            {
                var size = new Size(this.ActualWidth, this.ActualHeight);
              
                var res = ScaleDao.Instance.Delete(vo?.mScale);

                if (res == 1)
                {
                    this.mScaleVos?.Remove(vo);
                    this.DataLv.ItemsSource = null;
                    this.DataLv.ItemsSource = this.mScaleVos;
                    CommonFunction.AlertInfo("操作成功");
                }
                else if (res == -1)
                {
                    CommonFunction.AlertInfo("操作失败：该分类下有数据，不能删除！");
                }
                else
                {
                   CommonFunction.AlertInfo("操作失败");
                    Growl.ErrorGlobal("操作失败");
                }
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isEdit)
            {
                Eidt();
            }
            else
            {
                Insert();
            }
        }

        private void Insert()
        {
            Scale scale = new Scale
            {
                id = IdHelper.LongID,
                brand = mCurrentScale?.Brand,
                com = mCurrentScale.Com,
                series = mCurrentScale?.Series,
                name = this.nameTb.Text.Trim(),
                defaultType = 0,
                brandType = (int)mCurrentScale?.BrandType,
                companyId = App.CurrentCompanyVo.Id,
                clientId = App.InitConfig.clientId
            };
            if (!scale.brandType.HasValue)
            {
                scale.brandType = (int)ScaleBrandType.YH;
            }
            if (this.inRb.IsChecked == true)
            {
                scale.defaultType = (int)WeightingBillType.Buy;
            }
            if (this.outRb.IsChecked == true)
            {
                scale.defaultType = (int)WeightingBillType.Sale;
            }
            if (scale.name.IsNullOrEmpty() || !scale.name.Length.IsBetween(2, 10))
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("名称的长度为2到10 个字之间", this);
                return;
            }
            if (this.localScaleRb.IsChecked == true)
            {
                if (scale.com.IsNullOrEmpty() || scale.com.Length < 4)
                {
                    this.saveBtn.IsChecked = false;
                    CommonFunction.AlertInfo("没有选择可用的COM 串口", this);
                    return;
                }
                if (ScaleDao.Instance.IsExist(scale))
                {
                    this.saveBtn.IsChecked = false;
                    CommonFunction.AlertInfo("已经存在或者串口已经被使用", this);
                    return;
                }
                scale.baudRate = mCurrentScale.BaudRate;
                if (scale.baudRate < 1200 || scale.baudRate > 115200)
                {
                    this.saveBtn.IsChecked = false;
                    CommonFunction.AlertInfo("没有选择可用波特率", this);
                    return;
                }
            }

            scale.isDelete = 0;
            scale.addTime = DateTime.Now;
            scale.addUserId = App.CurrentUser.Id;
            scale.addUserName = App.CurrentUser.name;
            scale.isVirtual = this.virtualScaleRb.IsChecked ?? false;
            scale.isShare = this.ShareCb.IsChecked ?? false;
            var res = ScaleDao.Instance.Sqlite.Insert(scale);

            if (res > 0)
            {
                this.saveBtn.IsChecked = false;
                this.AddDrawerRight.IsOpen = false;
                Growl.SuccessGlobal("保存成功！");
                this.mScaleVos?.Insert(0, new ScaleVo(scale));
                this.DataLv.ItemsSource = null;
                this.DataLv.ItemsSource = mScaleVos;
                ResertInput();
            }
            else
            {
                this.saveBtn.IsChecked = false;
                string msg = "保存数据失败！";
                CommonFunction.AlertInfo(msg);
            }
        }

        private void Eidt()
        {
            if (mCurrentScale == null)
            {
                ResertInput();
                return;
            }

            String name = this.nameTb.Text.Trim();
            if (!name.Length.IsBetween(2, 10))
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("名称的长度为2到10 个字之间", this);
                return;
            }
            mCurrentScale.Name = name;
            if (this.inRb.IsChecked == true)
            {
                mCurrentScale.DefaultType = (int)WeightingBillType.Buy;
            }
            else
            {
                mCurrentScale.DefaultType = (int)WeightingBillType.Sale;
            }
            mCurrentScale.IsVirtual = this.virtualScaleRb.IsChecked ?? false;
            mCurrentScale.IsShare = this.ShareCb.IsChecked ?? false;
            var res = ScaleDao.Instance.Sqlite.Update(mCurrentScale.mScale);
            if (res > 0)
            {
                this.saveBtn.IsChecked = false;
                Growl.SuccessGlobal("保存成功！");
                this.AddDrawerRight.IsOpen = false;
                isEditing = false;
                FillData();
                ResertInput();
            }
            else
            {
                this.saveBtn.IsChecked = false;
                string msg = "保存数据失败！";
               CommonFunction.AlertInfo(msg);
            }

        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            isEditing = false;
            this.AddDrawerRight.IsOpen = false;
        }
        /// <summary>
        /// 修改时设置值 
        /// </summary>
        private void BindEditValue(Scale? scale)
        {
            isBindingValue = true;
            if (scale == null) return;

            this.nameTb.Text = scale.name;

            for (int i = 0; i < mScaleBrandVos?.Count; i++)
            {
                if (mScaleBrandVos[i].BrandName == scale.brand)
                {
                    this.brandCb.SelectedIndex = i;
                }
            }

            if (brandCb.SelectedIndex > -1)
            {
                var id = (brandCb.SelectedItem as ScaleBrand)?.id ?? 0;
                SetSeriesItemSource(id);
            }

            for (int i = 0; i < mScaleSeriesVos?.Count; i++)
            {
                if (mScaleSeriesVos[i].Name == scale.series)
                {
                    this.seriesCb.SelectedIndex = i;
                }
            }

            if (scale.defaultType == (int)WeightingBillType.Buy)
            {
                this.inRb.IsChecked = true;
            }
            else
            {
                this.outRb.IsChecked = true;
            }
            this.localScaleRb.IsChecked = scale.isVirtual ? false : true;
            this.virtualScaleRb.IsChecked = scale.isVirtual ? true : false;
            this.ShareCb.IsChecked = scale.isVirtual;

            isBindingValue = false;
        }

        private void ResertInput()
        {
            this.AddDrawerRight.IsOpen = false;
            this.nameTb.Text = "";
            this.comCb.SelectedIndex = -1;
            this.brandCb.SelectedIndex = -1;
            this.seriesCb.SelectedIndex = -1;
            this.rateCb.SelectedIndex = -1;
            this.saveBtn.IsChecked = false;
        }

        private void SetSeriesItemSource(Int64 brandId)
        {
            mScaleSeriesVos = null;
            var list = ScaleSeriesDao.Instance.GetListByBrandId(brandId);
            mScaleSeriesVos = list.Select((i) => { return new ScaleSeriesVo(i); }).ToList();
            this.seriesCb.SelectedIndex = -1;
            this.seriesCb.ItemsSource = mScaleSeriesVos;
        }

        private void ComCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is System.Windows.Controls.ComboBox cb)
            {
                if (cb.SelectedIndex > -1)
                {
                    var com = this.comCb.SelectedItem.ToString();
                    mCurrentScale.Com = com;
                }
            }
        }

        private void seriesCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.seriesCb.SelectedIndex > -1)
            {
                this.mCurrentScale.Series = (this.seriesCb.SelectedItem as ScaleSeriesVo).Name;
            }
        }

        private void BrandCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.brandCb.SelectedIndex < 0) return;
            var vo = this.brandCb.SelectedItem as ScaleBrandVo;
            this.mCurrentScale ??= new ScaleVo(new Scale());
            this.mCurrentScale.Brand = vo?.BrandName;
            this.mCurrentScale.BrandType = (ScaleBrandType)vo.Type;
            SetSeriesItemSource(vo.Id);
        }

        private void RateCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.rateCb.SelectedIndex < 0) return;
            var item = this.rateCb.SelectedItem as ComboBoxItem;
            this.mCurrentScale.BaudRate = Convert.ToInt32(item.Content);
        }

        private void RefreshBtn_Click(object sender, RoutedEventArgs e)
        {
            FillData();
        }

        private void Scale_Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e?.Key == Key.Escape) this.Close();
        }

        private void localScaleRb_Checked(object sender, RoutedEventArgs e)
        {
            this.ShareCb.Visibility = Visibility.Visible;
            this.comCb.Visibility = Visibility.Visible;
            this.rateCb.Visibility = Visibility.Visible;
        }

        private void localScaleRb_Unchecked(object sender, RoutedEventArgs e)
        {
            this.ShareCb.Visibility = Visibility.Collapsed;
            this.comCb.Visibility = Visibility.Collapsed;
            this.rateCb.Visibility = Visibility.Collapsed;
        }
    }
}

